package de.tudresden.st.cbse.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import de.tudresden.st.cbse.calendar.Calendar;
import de.tudresden.st.cbse.calendar.appointment.Appointment;
import de.tudresden.st.cbse.calendar.appointment.AppointmentType;
import de.tudresden.st.cbse.util.RemoteLookup;



@WebServlet({"/calendarAjax"})
public class CalendarAjaxServlet extends HttpServlet {
    private static final long serialVersionUID = 8895301509413413624L;

    private boolean validateAuthentication(HttpServletRequest req) {
        return req.getSession(true).getAttribute("currentSessionUser") != null;
    }
    
   
	@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (!validateAuthentication(req)) {
            resp.sendRedirect("index.jsp");
            return;
        }
              
        SimpleDateFormat formatter = new SimpleDateFormat("MMddyyHHmm");
        Date start=null;
        Date end = null;
        boolean noStartOrEnd=false;
		try {
		    start= new Date(Long.parseLong(req.getParameter("start"))*1000);
	        end= new Date(Long.parseLong(req.getParameter("end"))*1000);
			
			SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm", Locale.GERMANY);
	        System.out.println("*** Try to get appointments from "+sdf.format(start)+" - "+sdf.format(end)+")");
		} catch (NumberFormatException e) {
	    	noStartOrEnd= true;
		}
		
        
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        JSONArray jsonData= new JSONArray();
        
        String color="#868686";
        try {
        	Iterable<Appointment> appointments;
            Calendar userCalendar=RemoteLookup.getCalendarManager().getCalendarForUser((String)req.getSession(true).getAttribute("currentSessionUser"));
            if(noStartOrEnd)  appointments=userCalendar.get();
            else appointments=userCalendar.get(start, end);
                        
            for(Appointment appointment: appointments){
            	JSONObject jsonObject= new JSONObject();
            	jsonObject.put("title", appointment.getTitle());
            	jsonObject.put("start", appointment.getStart().toString());
            	jsonObject.put("end", appointment.getEnd().toString());
            	AppointmentType type= appointment.getType();
            	switch(type){
            	case FREE:
            		color="#128628";
            		break;

            	case BLOCKED:
            		color="#7e041e";
            		break;

            	case POTENTIALLY_BLOCKED:
            		color="#b15f08";
            		break;

            	case AWAY:
            		color="#0f3375";
            		break;

            	default:
            		color="#868686";
            		break;
            	}
            	jsonObject.put("color", color);
            	jsonData.add(jsonObject);
            	
            }
            
            	
   		
        } catch (NamingException e) {
            e.printStackTrace();
        }
        out.print(jsonData.toJSONString());
        out.flush();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    
    
}
